package sto.orz.json;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import sto.orz.rptp.model.Dataset;
import sto.orz.sql.ConnectionManager;
import sto.orz.sql.DBCPConnectionManager;

public class JSONDataset implements JSONAdapter {
	ConnectionManager connectionManager;
	Map data;
	Dataset dataset;

	public JSONDataset(Dataset dataset) {
		// TODO 转由 spring ioc
		this.data = new HashMap();
		this.connectionManager = new DBCPConnectionManager();
		this.dataset = dataset;
	}

	public void find() {
		Connection connection = null;
		PreparedStatement statement = null;
		ResultSet rs = null;
		String query = dataset.getQuery();

		try {
			connection = connectionManager.getConnection(dataset
					.getDatasource());
			statement = connection.prepareStatement(query,
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY);
			rs = statement.executeQuery();
			this.toArray(rs);
			rs.last();
			// Integer totalCount = rs.getRow();
		} catch (SQLException sqle) {
			// TODO: change to a customize execption
			throw new RuntimeException("Generate report error", sqle);
		} finally {
			try {
				rs.close();
			} catch (Exception e) {
			}
			try {
				statement.close();
			} catch (Exception e) {
			}
			try {
				connection.close();
			} catch (Exception e) {
			}
		}
	}

	private void toArray(ResultSet rs) throws SQLException {
		JSONObject j;
		net.sf.json.util.JSONDynaBean bean = new net.sf.json.util.JSONDynaBean();

		// TODO 重构参数
		int startIndex = 0;
		int offset = 10000;
		// 整理元数据
		ResultSetMetaData rsmd = rs.getMetaData();
		int numberOfColumns = rsmd.getColumnCount();
		String[] headerNames = new String[numberOfColumns];
		for (int i = 0; i < numberOfColumns; i++) {
			headerNames[i] = rsmd.getColumnName(i + 1);
		}
		data.put("column",headerNames);

		// 整理数据
		int columnLength = headerNames.length;
		int count = 0;
		List columns = new ArrayList();

		if (startIndex > 0) {
			rs.absolute(startIndex);
		}
		while (count < offset && rs.next()) {
			Object[] values = new Object[columnLength];
			for (int i = 0; i < columnLength; i++) {
				values[i] = rs.getObject(i + 1);
			}
			columns.add(values);
			count++;
		}

		data.put("data", columns);
		//j = JSONObject.fromObject(m);
		//bean.toString()
		//j.fromDynaBean(bean);
		//System.out.println(j.toString());
	}

	public String toJson() {
		this.find();
		// JSONArray jsonArray = JSONArray.fromObject(columns);
		return JSONObject.fromObject(data).toString();
	}
}
